
<template>
  <div class="search">
    <Card>
      <Row class="operation">
        <Button @click="add" type="primary" icon="md-add">添加子分类</Button>
        <Button @click="addRoot" icon="md-add">添加一级分类</Button>
        <Button @click="delAll" icon="md-trash">删除</Button>
        <Button @click="getParentList" icon="md-refresh">刷新</Button>
        <!-- <i-switch v-model="strict" size="large" style="margin-left:5px">
          <span slot="open">级联</span>
          <span slot="close">单选</span>
        </i-switch> -->
      </Row>
      <Row type="flex" justify="start" class="code-row-bg">
        <Col span="6">
          <Alert show-icon>
            当前选择编辑：
            <span class="select-title">{{editTitle}}</span>
            <a class="select-clear" v-if="form.id" @click="cancelEdit">取消选择</a>
          </Alert>
          <!-- <Input
            v-model="searchKey"
            suffix="ios-search"
            @on-change="search"
            placeholder="输入分类ID"
            clearable
          /> -->
          <div class="tree-bar" :style="{maxHeight: maxHeight}">
            <Tree
              ref="tree"
              :data="data"
              :load-data="loadData"
              @on-check-change="changeSelect"
              @on-select-change="selectTree"
              :check-strictly="!strict"
            ></Tree>
          </div>
          <Spin size="large" fix v-if="loading"></Spin>
        </Col>
        <Col span="9" style="margin-left:10px">
          <Form ref="form" :model="form" :label-width="85">
            <FormItem label="名称" prop="title">
              <i-input type="text" v-model="form.title"></i-input>
            </FormItem>
            <FormItem label="图片" prop="pic" >
          <upload-pic-input v-model="form.pic"></upload-pic-input>
        </FormItem>
            <FormItem label="排序值" prop="sortOrder">
              <InputNumber :max="1000" :min="0" v-model="form.sortOrder"></InputNumber>
              <span style="margin-left:5px">值越小越靠前，支持小数</span>
            </FormItem>
            <FormItem label="是否启用" prop="status">
              <i-switch size="large" v-model="form.status" :true-value="0" :false-value="-1">
                <span slot="open">启用</span>
                <span slot="close">禁用</span>
              </i-switch>
            </FormItem>
            <Form-item>
              <Button
                style="margin-right:5px"
                @click="submitEdit"
                :loading="submitLoading"
                type="primary"
                icon="ios-create-outline"
              >修改并保存</Button>
              <Button @click="handleReset">重置</Button>
            </Form-item>
          </Form>
        </Col>
      </Row>
    </Card>

    <Modal :title="modalTitle" v-model="modalVisible" :mask-closable="false" :width="500">
      <Form ref="formAdd" :model="formAdd" :label-width="100" :rules="formValidate">
        <div v-if="showParent">
          <FormItem label="上级分类：">{{form.title}}</FormItem>
        </div>
        <FormItem label="分类名称" prop="title">
          <Input v-model="formAdd.title"/>
        </FormItem>
        <FormItem label="排序值" prop="sortOrder">
          <InputNumber :max="1000" :min="0" v-model="formAdd.sortOrder"></InputNumber>
          <span style="margin-left:5px">值越小越靠前，支持小数</span>
        </FormItem>
         <FormItem label="图片" prop="pic" >
          <upload-pic-input v-model="formAdd.pic"></upload-pic-input>
        </FormItem>
        <!-- <FormItem label="是否为父节点" :true-value="true" :false-value="false">
              <i-switch v-model="formAdd.isParent">
                <span slot="open">是</span>
                <span slot="close">否</span>
              </i-switch>
            </FormItem> -->
        <FormItem label="是否启用" prop="status">
          <i-switch size="large" v-model="formAdd.status" :true-value="0" :false-value="-1">
            <span slot="open">启用</span>
            <span slot="close">禁用</span>
          </i-switch>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelAdd">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submitAdd">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import uploadPicInput from "@/views/my-components/xboot/upload-pic-input.vue"
export default {
   components: {
    uploadPicInput
    // departmentTreeChoose
  },
  data() {
    return {
      id:'',
      loading: true,
      maxHeight: "500px",
      strict: true,
      userLoading: false,
      loadingEdit: true,
      modalVisible: false,
      selectList: [],
      selectCount: 0,
      showParent: false,
      modalTitle: "",
      editTitle: "",
      searchKey: "",
      form: {
        id: "",
        title: "",
        pic:'',
        parentId: "",
        sortOrder: 0,
        status: 0
      },
      formAdd: {
        title: "",
        pic:'',
        parentId: "",
        sortOrder: 0,
        status: 0
      },
      formValidate: {
        title: [{ required: true, message: "名称不能为空", trigger: "blur" }]
      },
      submitLoading: false,
      data: [],
      dataEdit: [],
      users: []
    };
  },
  methods: {
    init() {
      this.getParentList();
      // this.getParentListEdit();
    },
  //  getTree(tree = []) {
  //       let arr = [];
  //       if (!!tree && tree.length !== 0) {
  //           tree.forEach(item => {
  //               let obj = {};
  //               obj.title = item.title;
  //               obj.id =item.id; // 其他你想要添加的属性
  //               obj.parentId = item.parentId;
  //               obj.pic = item.pic;
  //               obj.sortOrder = item.sortOrder;
  //               obj.isParent = item.isParent;
  //               obj.status = item.status;
  //               obj.children = this.getTree(item.backAreaVOS); // 递归调用
  //               arr.push(obj);
  //           });
  //       }
  //       return arr;
  //   },
    getParentList() {
      this.loading = true;
        this.postRequest("/goodCategory/getGoodCategoryList").then(res => {
        this.loading = false;
        if (res.success) {
          res.result.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          this.data = res.result;
        }
      });
    },
    loadData(item, callback) {
      var data = {
        parentId: item.id
      }
      this.postRequest("/goodCategory/getGoodCategoryList", data).then(res => {
        if (res.success) {
          res.result.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          callback(res.result);
        }
      });
    },
    getParentListEdit() {
    //   this.loadingEdit = true;
    //  this.postRequest("/classification/getCategoryList").then(res => {
    //     this.loadingEdit = false;
    //     if (res.success) {
    //         console.log(res)
    //       this.dataEdit = this.getTree(res.result.data)
    //     }
    //   });
    },
    search() {
    //   if (this.searchKey) {
    //     this.loading = true;
    //     searchDepartment({ title: this.searchKey }).then(res => {
    //       this.loading = false;
    //       if (res.success) {
    //         this.data = res.result;
    //       }
    //     });
    //   } else {
    //     this.getParentList();
    //   }
    },
    selectTree(v) {
        console.log(1111)
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        this.editTitle = data.title;
        // 回显
        this.form = data;
      } else {
        this.cancelEdit();
      }
    },
    cancelEdit() {
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.$refs.form.resetFields();
      delete this.form.id;
      this.editTitle = "";
    },
    selectTreeEdit(v) {
        console.log(v)
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        // console.log(data)
        this.id = data.id;
        this.form.title = data.title;
      }
    },
    cancelAdd() {
      this.modalVisible = false;
    },
    handleReset() {
      this.$refs.form.resetFields();
      this.form.status = 0;
    },
    submitEdit() { 
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(11111)
          if (!this.form.id) {
            this.$Message.warning("请先点击选择要修改的部门");
            return;
          }
          console.log(this.form)
          this.submitLoading = true;
          this.postRequest("/goodCategory/updateGoodCategory",this.form).then(res => {
            this.submitLoading = false;
            if (res.success) {
              this.$Message.success("编辑成功");
              this.init();
              this.modalVisible = false;
            }
          })
        }
      });
    },
    submitAdd() {
      this.$refs.formAdd.validate(valid => {
        if (valid) {
          console.log(this.formAdd)
          this.submitLoading = true;
          this.postRequest("/goodCategory/insertGoodCategory",this.formAdd).then(res => {
            this.submitLoading = false;
            if (res.success) {
              this.$Message.success("添加成功");
              this.init();
              this.modalVisible = false;
            }
          });
        }
      });
    },
    add() {
      console.log(this.form.parentId)
      if (this.form.parentId == "" || this.form.parentId == null) {
        this.$Message.warning("请先点击选择一个分类");
        return;
      }
      this.modalTitle = "添加子分类";
      this.showParent = true;
      this.formAdd = {
        // isParent:false,
        parentId: this.form.id,
        sortOrder: this.formAdd.sortOrder,
        status: this.formAdd.status,
      };
      this.modalVisible = true;
    },
    addRoot() {
      this.modalTitle = "添加一级分类";
      this.showParent = false;
      this.formAdd = {
        // isParent:true,
        sortOrder: this.formAdd.sortOrder,
        status: this.formAdd.status,
        parentId: 0,
      };
      this.modalVisible = true;
    },
    changeSelect(v) {
      console.log(v)
      this.selectCount = v.length;
      this.selectList = v;
    },
    delAll() {
      if (this.form.id =='') {
        this.$Message.warning("您还未勾选要删除的数据");
        return;
      }
      var params ={
        id:this.form.id
      }
      console.log(params)
      this.postRequest("/goodCategory/deleteGoodCategory",params).then(res =>{
        console.log(res)
        if(res.success){
          this.$Message.success("删除成功");
          this.init()
        }
      })
    //   if (this.selectCount <= 0) {
    //     this.$Message.warning("您还未勾选要删除的数据");
    //     return;
    //   }
    //   this.$Modal.confirm({
    //     title: "确认删除",
    //     content: "您确认要删除所选的 " + this.selectCount + " 条数据及其下级所有数据?",
    //     onOk: () => {
    //       let ids = "";
    //       this.selectList.forEach(function(e) {
    //         ids += e.id + ",";
    //       });
    //       ids = ids.substring(0, ids.length - 1);
    //       deleteDepartment(ids).then(res => {
    //         if (res.success) {
    //           this.$Message.success("删除成功");
    //           this.selectList = [];
    //           this.selectCount = 0;
    //           this.cancelEdit();
    //           this.init();
    //         }
    //       });
    //     }
    //   });
     }
  },
  mounted() {
    // 计算高度
    let height = document.documentElement.clientHeight;
    this.maxHeight = Number(height - 287) + "px";
    this.init();
  }
};
</script>

<style  scoped>

    .operation {
        margin-bottom: 2vh;
    }
    .select-count {
        font-size: 13px;
        font-weight: 600;
        color: #40a9ff;
    }
    .select-title {
        font-size: 12px;
        font-weight: 600;
        color: #40a9ff;
    }
    .select-clear {
        margin-left: 10px;
    }
    .page{
        margin-top: 2vh;
    }
    .drop-down{
        font-size: 13px;
        margin-left: 5px;
    }



    .ivu-tree-empty {
        margin-top: 10px;
    }


.tree-bar {
    overflow: auto;
    margin-top: 5px;
}

.tree-bar::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

.tree-bar::-webkit-scrollbar-thumb {
    border-radius: 4px;
    -webkit-box-shadow: inset 0 0 2px #d1d1d1;
    background: #e4e4e4;
}

.ivu-tree .ivu-tree-empty {
    margin-top: 10px;
    font-size: 12px;
}
</style>